require("colors");
const md5 = require("md5");
const express = require("express");
const handleDb = require("../db/handleDb");

router = express.Router();  // 页面路由

router.post("/register", (req, res) => {

       

        (async function register(){
            let {username, image_code, password, agree} = req.body;
            // 获取session中的验证码
            const capImage = req.session.captcha;

            // 进行判断验证
            if(!username || !image_code  || !password || !agree){
                res.json({errno: 1, errmsg: "有未填写的数据"});
                return;
            } 
            
            // 验证码校验
            if (image_code.toLocaleLowerCase() != capImage.toLocaleLowerCase()){
                res.json({errno: 1, errmsg: "验证码有误，请重新输入"});
                return;
            }
            
            // 查询数据是否存在该用户名
            let hasAccount = await handleDb(res, "info_user", "find", "数据出错", `username="${username}"`);
            if(hasAccount.length > 0){
                res.json({errmsg: "该用户已注册"});
                return;
            }

            // 注册用户，保存数据
            // 密码采用MD5加密
            let result = await handleDb(res, "info_user", "insert", "数据库操作失败",
            {
                username: username,
                password_hash: md5(password),
                nick_name: username
            });

            // 添加注册成功的session信息
            req.session["sessionId"] = result.insertId;

            res.json({errno: 0, errmsg: "注册成功"});
        })();

});

module.exports = router;